package com.egg.ylt.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.egg.ylt.R;
import com.egg.ylt.Utils.API;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.DateUtils;
import com.egg.ylt.Utils.StringSpanUtils;
import com.egg.ylt.activity.ACT_EditBabyInfo;
import com.egg.ylt.activity.ACT_PhoneInvite;
import com.egg.ylt.activity.ACT_SelectBaby;
import com.egg.ylt.activity.ACT_SelectShopList;
import com.egg.ylt.activity.ACT_SwimHistory;
import com.egg.ylt.activity.ACT_UserLogin;
import com.egg.ylt.activity.ACT_WebView;
import com.egg.ylt.heartbeat.HeartbeatManageSingleton;
import com.egg.ylt.pojo.CaloriesEntity;
import com.egg.ylt.pojo.CurrentBabyInfoEntity;
import com.egg.ylt.pojo.MemberBabyEntity;
import com.egg.ylt.pojo.NatatoriumListPageEntity;
import com.egg.ylt.pojo.RealTimeHealthyDataEntity;
import com.egg.ylt.pojo.RealtimeDataEntity;
import com.egg.ylt.pojo.SwimHistoryEntity;
import com.egg.ylt.presenter.impl.SwimPresenterImpl;
import com.egg.ylt.view.ISwimView;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.ruffian.library.widget.RImageView;
import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yonyou.framework.library.base.BaseFragment;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.DisplayUtil;
import com.yonyou.framework.library.dialog.AlertDialog;
import com.yonyou.framework.library.eventbus.EventCenter;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author:        yupeng
 * created on:    2019/2/26 20:48
 * description:   健康/游泳界面
 */
public class FRA_Swim extends BaseFragment<SwimPresenterImpl> implements ISwimView {
    // 找门店
    private final int REQUEST_CODE_FOR_SELECT = 100;
    // 游泳圈
    private final int REQUEST_CODE_FOR_RING = REQUEST_CODE_FOR_SELECT + 1;
    // 抚触台
    private final int REQUEST_CODE_FOR_STEELYARD = REQUEST_CODE_FOR_SELECT + 2;

    @BindView(R.id.iv_banner_img)
    ImageView ivBannerImg;
    @BindView(R.id.record_babyhead_riv)
    RImageView recordBabyheadRiv;
    @BindView(R.id.record_babyname_tv)
    TextView recordBabynameTv;
    @BindView(R.id.record_modify_iv)
    ImageView recordModifyIv;
    @BindView(R.id.record_babybirth_tv)
    TextView recordBabybirthTv;
    @BindView(R.id.record_babyinfo_ll)
    LinearLayout recordBabyinfoLl;
    @BindView(R.id.record_invitehomie_tv)
    RTextView recordInvitehomieTv;
    @BindView(R.id.icon_fire)
    ImageView iconFire;
    @BindView(R.id.calorie_txt)
    TextView calorieTxt;
    @BindView(R.id.icon_ring)
    ImageView iconRing;
    @BindView(R.id.time_txt)
    TextView timeTxt;
    @BindView(R.id.baby_swim_data_layout)
    RLinearLayout babySwimDataLayout;
    @BindView(R.id.record_title_babylist_iv)
    ImageView recordTitleBabylistIv;
    @BindView(R.id.myt)
    Toolbar myt;
    @BindView(R.id.appointment_appbar)
    AppBarLayout appointmentAppbar;
    @BindView(R.id.find_shop_button)
    RTextView findShopButton;
    @BindView(R.id.detail_shop_button)
    RTextView detailShopButton;
    @BindView(R.id.select_shop_normal_layout)
    RLinearLayout selectShopNormalLayout;
    @BindView(R.id.shop_icon_riv)
    RImageView shopIconRiv;
    @BindView(R.id.shop_name_txt)
    TextView shopNameTxt;
    @BindView(R.id.shop_selected_time_txt)
    TextView shopSelectedTimeTxt;
    @BindView(R.id.select_shop_button)
    RTextView selectShopButton;
    @BindView(R.id.pm_label)
    TextView pmLabel;
    @BindView(R.id.pm_image)
    ImageView pmImage;
    @BindView(R.id.pm_data_txt)
    TextView pmDataTxt;
    @BindView(R.id.air_temperature_label)
    TextView airTemperatureLabel;
    @BindView(R.id.air_temperature_image)
    ImageView airTemperatureImage;
    @BindView(R.id.air_temperature_data_txt)
    TextView airTemperatureDataTxt;
    @BindView(R.id.humidity_label)
    TextView humidityLabel;
    @BindView(R.id.humidity_image)
    ImageView humidityImage;
    @BindView(R.id.humidity_data_txt)
    TextView humidityDataTxt;
    @BindView(R.id.formaldehyde_label)
    TextView formaldehydeLabel;
    @BindView(R.id.formaldehyde_image)
    ImageView formaldehydeImage;
    @BindView(R.id.formaldehyde_data_txt)
    TextView formaldehydeDataTxt;
    @BindView(R.id.ph_label)
    TextView phLabel;
    @BindView(R.id.ph_image)
    ImageView phImage;
    @BindView(R.id.ph_data_txt)
    TextView phDataTxt;
    @BindView(R.id.turbidity_label)
    TextView turbidityLabel;
    @BindView(R.id.turbidity_image)
    ImageView turbidityImage;
    @BindView(R.id.turbidity_data_txt)
    TextView turbidityDataTxt;
    @BindView(R.id.water_temperature_label)
    TextView waterTemperatureLabel;
    @BindView(R.id.water_temperature_image)
    ImageView waterTemperatureImage;
    @BindView(R.id.water_temperature_data_txt)
    TextView waterTemperatureDataTxt;
    @BindView(R.id.select_shop_selected_layout)
    RLinearLayout selectShopSelectedLayout;
    @BindView(R.id.connect_ring_button)
    RTextView connectRingButton;
    @BindView(R.id.detail_ring_button)
    RTextView detailRingButton;
    @BindView(R.id.swim_ring_normal_layout)
    RLinearLayout swimRingNormalLayout;
    @BindView(R.id.swim_ring_img)
    ImageView swimRingImg;
    @BindView(R.id.select_swim_ring_button)
    RTextView selectSwimRingButton;
    @BindView(R.id.calorie_img)
    ImageView calorieImg;
    @BindView(R.id.swim_calorie_txt)
    TextView swimCalorieTxt;
    @BindView(R.id.calorie_label)
    TextView calorieLabel;
    @BindView(R.id.swim_time_txt)
    TextView swimTimeTxt;
    @BindView(R.id.swim_ring_connected_layout)
    RLinearLayout swimRingConnectedLayout;
    @BindView(R.id.connect_steelyard_button)
    RTextView connectSteelyardButton;
    @BindView(R.id.detail_steelyard_button)
    RTextView detailSteelyardButton;
    @BindView(R.id.steelyard_normal_layout)
    RLinearLayout steelyardNormalLayout;
    @BindView(R.id.steelyard_img)
    ImageView steelyardImg;
    @BindView(R.id.select_steelyard_button)
    RTextView selectSteelyardButton;
    @BindView(R.id.steelyard_height_txt)
    TextView steelyardHeightTxt;
    @BindView(R.id.steelyard_weight_txt)
    TextView steelyardWeightTxt;
    @BindView(R.id.steelyard_connect_success_layout)
    RLinearLayout steelyardConnectSuccessLayout;
    @BindView(R.id.steelyard_data_img)
    ImageView steelyardDataImg;
    @BindView(R.id.select_steelyard_data_button)
    RTextView selectSteelyardDataButton;
    @BindView(R.id.steelyard_connect_data_layout)
    RLinearLayout steelyardConnectDataLayout;
    @BindView(R.id.record_parent)
    CoordinatorLayout recordParent;

    private AlertDialog inviteDialog;

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {
        initViewsAndEvents();
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {
        if (!mPresenter.isUserLogin()) {
            recordBabynameTv.setText("未登录");
            recordBabybirthTv.setText("");
            return;
        }

        mPresenter.onInit();
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fra_swim;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.SWITCH_BABY_EVENT: // 切换宝宝
                String checkedBabyId = (String) eventCenter.getData();
                if (TextUtils.isEmpty(checkedBabyId) || checkedBabyId.equals(mPresenter.getCurrentBabyModel().getBabyId())) {
                    return;
                }

                new AppSharedPreferences(getActivity()).putString(Constants.SWIM_RING_CODE, "");
                Constants.SWIMRINGCODE = "";
                initializeInterfaceAndClearData();
                mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, checkedBabyId);
                break;

            case Constants.CLEAR_SWIM_FRAGMENT: // 清理界面
                initializeInterfaceAndClearData();
                break;

            case Constants.INIT_SWIM_FRAGMENT: // 初始化界面
                //mPresenter.onInit();
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void showToast(String msg) {
        CommonUtils.makeEventToast(getActivity(), msg, false);
    }

    @Override
    public void initializeBabyInfo() {
        recordBabynameTv.setText(mPresenter.hasAddedBaby() ? mPresenter.getCurrentBabyModel().getName() : "未添加宝宝");
        recordBabybirthTv.setText(mPresenter.hasAddedBaby() ? mPresenter.getCurrentBabyModel().getBirthday() : "");
        recordModifyIv.setVisibility(mPresenter.hasAddedBaby() ? View.VISIBLE : View.GONE);
        babySwimDataLayout.setClickable(mPresenter.hasAddedBaby());

        if (mPresenter.hasAddedBaby()) {
            mPresenter.getBabySwimData(mPresenter.getCurrentBabyModel().getBabyId());
            Glide.with(this).load(mPresenter.getCurrentBabyModel().getImageUrl()).error(getResources().getDrawable(R.drawable.healthdata_icon_headportrait_default)).into(recordBabyheadRiv);
        }
    }

    @Override
    public void showBabySwimData(SwimHistoryEntity model) {
        calorieTxt.setText(model.getCaloriesSum());
        timeTxt.setText(model.getTimeSum());
    }

    @Override
    public void showShopRealTimeData(RealtimeDataEntity model) {
        if (model == null) {
            return;
        }
        selectShopNormalLayout.setVisibility(View.GONE);
        selectShopSelectedLayout.setVisibility(View.VISIBLE);

        // 空气
        for (RealtimeDataEntity.AirBean air : model.getAir()) {
            // 1 PM2.5 2 温度 3 湿度 4 甲醛
            switch (air.getType()) {
                case "1":
                    pmDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), air.getNum())
                            .addRelativeScale(1.8f, " " + air.getStatus()).build());
                    break;

                case "2":
                    airTemperatureDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), air.getNum())
                            .addRelativeScale(1.8f, " " + air.getStatus()).build());
                    break;

                case "3":
                    humidityDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), air.getNum())
                            .addRelativeScale(1.8f, " " + air.getStatus()).build());
                    break;

                case "4":
                    formaldehydeDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), air.getNum())
                            .addRelativeScale(1.8f, " " + air.getStatus()).build());
                    break;
            }
        }

        // 水
        for (RealtimeDataEntity.WaterBean water : model.getWater()) {
            // 1 ph 2 浑浊度 3 温度
            switch (water.getType()) {
                case "1":
                    phDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), water.getNum())
                            .addRelativeScale(1.8f, " " + water.getStatus()).build());
                    break;

                case "2":
                    turbidityDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), water.getNum())
                            .addRelativeScale(1.8f, " " + water.getStatus()).build());
                    break;

                case "3":
                    waterTemperatureDataTxt.setText(StringSpanUtils.init()
                            .addForegroundColorHighLight(getResources().getColor(R.color.shop_data_green), water.getNum())
                            .addRelativeScale(1.8f, " " + water.getStatus()).build());
                    break;
            }
        }
    }

    @Override
    public void showSteelyardConnectSucess() {
        steelyardNormalLayout.setVisibility(View.GONE);
        steelyardConnectSuccessLayout.setVisibility(View.VISIBLE);
        steelyardConnectDataLayout.setVisibility(View.GONE);

        // 请求抚触台长连接，获取数据后断开
        try {
            HeartbeatManageSingleton.getInstance.startSteelyardHeartbeat(new HeartbeatManageSingleton.OnHandleSteelyardEventCallback() {
                @Override
                public void onHandleSteelyardEvent(RealTimeHealthyDataEntity entity) {
                    if (TextUtils.isEmpty(entity.getHeight()) || TextUtils.isEmpty(entity.getWeight())) {
                        steelyardNormalLayout.setVisibility(View.GONE);
                        steelyardConnectSuccessLayout.setVisibility(View.VISIBLE);
                        steelyardConnectDataLayout.setVisibility(View.GONE);
                        return;
                    }

                    if ("0.0".equals(entity.getHeight()) && "0.0".equals(entity.getWeight())
                            || "0".equals(entity.getHeight()) && "0".equals(entity.getWeight())) {
                        steelyardNormalLayout.setVisibility(View.GONE);
                        steelyardConnectSuccessLayout.setVisibility(View.VISIBLE);
                        steelyardConnectDataLayout.setVisibility(View.GONE);
                    } else {
                        steelyardNormalLayout.setVisibility(View.GONE);
                        steelyardConnectSuccessLayout.setVisibility(View.GONE);
                        steelyardConnectDataLayout.setVisibility(View.VISIBLE);

                        steelyardHeightTxt.setText(entity.getHeight());
                        steelyardWeightTxt.setText(entity.getWeight());

                        HeartbeatManageSingleton.getInstance.stopSteelyardHeartbeat();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showSwimRingConncetSuccess(String equipCode) {
        try {
            HeartbeatManageSingleton.getInstance.startSwimringHeartbeat(new HeartbeatManageSingleton.OnHandleSwimringEventCallback() {
                @Override
                public void onHandleSwimringEvent(CaloriesEntity entity) {
                   if ("0".equals(entity.getStatus())) { // 绑定，开始轮询
                       swimRingNormalLayout.setVisibility(View.GONE);
                       swimRingConnectedLayout.setVisibility(View.VISIBLE);

                       swimCalorieTxt.setText(entity.getCalories());
                       swimTimeTxt.setText(formatMMss(entity.getTime()) == null ? "" : formatMMss(entity.getTime()));
                   } else if ("1".equals(entity.getStatus())) { // 取消绑定：断开轮询
                       HeartbeatManageSingleton.getInstance.stopSwimringHeartbeat();
                       Constants.SWIMRINGCODE = "";
                       new AppSharedPreferences(getActivity()).putString(Constants.SWIM_RING_CODE, "");
                       CommonUtils.makeEventToast(getActivity(), "该设备已与宝宝解绑", false);
                   }
                }
            }, equipCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.record_modify_iv, R.id.record_invitehomie_tv, R.id.find_shop_button,
            R.id.detail_shop_button, R.id.connect_ring_button, R.id.detail_ring_button, R.id.select_steelyard_data_button,
            R.id.connect_steelyard_button, R.id.detail_steelyard_button, R.id.baby_swim_data_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.record_modify_iv: // 编辑资料
                if (!checkUserInfo()) {
                    return;
                }
                if (mPresenter.getCurrentBabyModel().isIsAdmin()) {
                    gotoEditBabyInfoActivity(mPresenter.getCurrentBabyModel());
                } else {
                    showToast("您没有修改宝宝信息的权限");
                }
                break;

            case R.id.record_invitehomie_tv: // 邀请家人
                if (!checkUserInfo()) {
                    return;
                }
                if (!mPresenter.getCurrentBabyModel().isIsAdmin()) {
                    CommonUtils.makeEventToast(getActivity(), "您不是管理员，没有邀请权限", false);
                    return;
                }
                initInviteDialog();
                inviteDialog.show();
                break;

            case R.id.find_shop_button: // 找门店
                if (!checkUserInfo()) {
                    return;
                }
                readyGoForResult(ACT_SelectShopList.class, REQUEST_CODE_FOR_SELECT);
                break;

            case R.id.detail_shop_button: // 泳池详情
                Bundle bShop = new Bundle();
                bShop.putSerializable("title", "泳池详情");
                bShop.putSerializable("url", API.TIME_CARD_SHARE_URL + "?pageName=swimPool&isShare=false#/swimmingPool");
                readyGo(ACT_WebView.class, bShop);
                break;

            case R.id.connect_ring_button: // 连接泳圈
                if (!checkUserInfo()) {
                    return;
                }
                startScanForResult(REQUEST_CODE_FOR_RING);
                break;

            case R.id.detail_ring_button: // 泳圈详情
                Bundle bRing = new Bundle();
                bRing.putSerializable("title", "泳圈详情");
                bRing.putSerializable("url", API.TIME_CARD_SHARE_URL + "?pageName=swimCircle&isShare=false#/swimmingPool");
                readyGo(ACT_WebView.class, bRing);
                break;

            case R.id.connect_steelyard_button: // 抚触台
                if (!checkUserInfo()) {
                    return;
                }
                startScanForResult(REQUEST_CODE_FOR_STEELYARD);
                break;

            case R.id.detail_steelyard_button: // 抚触台详情
                Bundle bSteelyard = new Bundle();
                bSteelyard.putSerializable("title", "抚触台详情");
                bSteelyard.putSerializable("url", API.TIME_CARD_SHARE_URL + "?pageName=touchTable&isShare=false#/swimmingPool");
                readyGo(ACT_WebView.class, bSteelyard);
                break;

            case R.id.baby_swim_data_layout: // 游泳数据
                readyGo(ACT_SwimHistory.class);
                break;

            case R.id.select_steelyard_data_button: // 抚触台更换设备(常连接获取数据时)
                if (!checkUserInfo()) {
                    return;
                }
                HeartbeatManageSingleton.getInstance.stopSteelyardHeartbeat();
                startScanForResult(REQUEST_CODE_FOR_STEELYARD);
                break;

            case R.id.select_steelyard_button: // 抚触台更换设备(连接成功时)
                if (!checkUserInfo()) {
                    return;
                }
                HeartbeatManageSingleton.getInstance.stopSteelyardHeartbeat();
                startScanForResult(REQUEST_CODE_FOR_STEELYARD);
                break;

            case R.id.select_swim_ring_button: // 切换泳圈
                if (!checkUserInfo()) {
                    return;
                }
                startScanForResult(REQUEST_CODE_FOR_RING);
                break;
        }
    }

    /**
     * 校验用户：未登录跳转登录界面；未添加宝宝跳转添加宝宝界面
     *
     * @return
     */
    private boolean checkUserInfo() {
        if (!mPresenter.isUserLogin()) {
            readyGo(ACT_UserLogin.class);
            return false;
        }
        if (!mPresenter.hasAddedBaby()) {
            showToast("请先添加宝宝");
            readyGo(ACT_SelectBaby.class);
            return false;
        }
        return true;
    }

    /**
     * 初始化常链接UI：门店、泳圈、抚触台
     */
    private void initializeALLConnectInterface() {
        initializeShopConnectInterface();
        initializeSwimRingConnectInterface();
        initializeSteelyardConnectInterface();
    }

    /**
     * 初始化门店UI
     */
    private void initializeShopConnectInterface() {
        selectShopNormalLayout.setVisibility(View.VISIBLE);
        selectShopSelectedLayout.setVisibility(View.GONE);
    }

    /**
     * 初始化泳圈UI
     */
    private void initializeSwimRingConnectInterface() {
        swimRingNormalLayout.setVisibility(View.VISIBLE);
        swimRingConnectedLayout.setVisibility(View.GONE);
    }

    /**
     * 初始化抚触台UI
     */
    private void initializeSteelyardConnectInterface() {
        steelyardNormalLayout.setVisibility(View.VISIBLE);
        steelyardConnectDataLayout.setVisibility(View.GONE);
        steelyardConnectSuccessLayout.setVisibility(View.GONE);
    }

    /**
     * 开启扫描
     */
    private void startScanForResult(final int requestcode) {
        if (!XXPermissions.isHasPermission(mContext, Permission.CAMERA)) {
            XXPermissions.with((Activity) mContext).permission(Permission.CAMERA).request(new OnPermission() {

                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    if (isAll) {
                        readyGoForResult(CaptureActivity.class, requestcode);
                    }
                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                    CommonUtils.makeEventToast(mContext, "请开启相机权限后重试", false);
                }
            });
            return;
        }
        readyGoForResult(CaptureActivity.class, requestcode);

    }

    /**
     * 跳转编辑婴儿信息界面
     *
     * @param entity
     */
    private void gotoEditBabyInfoActivity(CurrentBabyInfoEntity entity) {
        Intent intent = new Intent(mContext, ACT_EditBabyInfo.class);
        MemberBabyEntity.ListBean listBean = new MemberBabyEntity.ListBean();
        listBean.setBabyId(entity.getBabyId());
        listBean.setBirthDay(entity.getDate());
        listBean.setGender(entity.getGender());
        listBean.setHeight(entity.getHeight());
        listBean.setWeight(entity.getWeight());
        listBean.setImageUrl(entity.getImageUrl());
        listBean.setName(entity.getName());
        listBean.setRelationshipId(entity.getRelationId());
        listBean.setRelationshipName(entity.getRelationName());
        intent.putExtra("bean", listBean);
        intent.putExtra("sex", entity.getGender());
        intent.putExtra(ACT_SelectBaby.KEY_RESOURCE_TYPE, ACT_EditBabyInfo.START_FROM_HEALTH);
        mContext.startActivity(intent);
    }

    /**
     * 邀请弹窗
     */
    private void initInviteDialog() {
        inviteDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_invitehomie_without_relationship)
                .setWidthAndHeight(mScreenWidth - DisplayUtil.dip2px(mContext, 20), ViewGroup.LayoutParams.WRAP_CONTENT)
                .setCancelableOntheOutside(true)
                .create();
        Window window = inviteDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        inviteDialog.getView(R.id.iv_wechat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inviteByWechat(mPresenter.getCurrentBabyModel().getRelationName(), 0);
                inviteDialog.dismiss();
            }
        });
        inviteDialog.getView(R.id.iv_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ACT_PhoneInvite.startAc(mContext, Constants.BABYID, mPresenter.getCurrentBabyModel().getName());
                inviteDialog.dismiss();
            }
        });
        inviteDialog.getView(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inviteDialog.dismiss();
            }
        });
    }

    private void inviteByWechat(String relationName, int type) {

        UMWeb web = new UMWeb(String.format("%s?token=%s&companyId=%s&babyId=%s&time=%s&name=%s&imgUrl=%s&relationName=%s",
                API.INVITE_WITHOUT_RELATIONSHIP, Constants.TOKEN, Constants.COMPANYID, mPresenter.getCurrentBabyModel().getBabyId(), System.currentTimeMillis(),
                mPresenter.getCurrentBabyModel().getName(), mPresenter.getCurrentBabyModel().getImageUrl(), relationName));//分享链接
        web.setTitle("宝宝的照片都在这里，快来看看吧!");//标题
        web.setDescription("来婴联通，全家的照片都在这");//描述

        SHARE_MEDIA shareMedia;
        switch (type) {
            case 0: //分享到微信
                shareMedia = SHARE_MEDIA.WEIXIN;
                break;

            case 1: //分享到微信朋友圈
                shareMedia = SHARE_MEDIA.WEIXIN_CIRCLE;
                break;

            default:
                shareMedia = SHARE_MEDIA.WEIXIN;
                break;
        }

        new ShareAction(getActivity())
                .setPlatform(shareMedia) //传入平台
                .withMedia(web) //分享链接
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        showToast("邀请成功");
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        showToast("邀请失败");
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                    }
                }).share();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK || data == null || data.getExtras() == null) {
            return;
        }

        switch (requestCode) {
            case REQUEST_CODE_FOR_SELECT: // 选择门店
                handleSelectShopEvent(data.getExtras());
                break;

            case REQUEST_CODE_FOR_RING: // 游泳圈
                handleConnectRingEvent(data.getExtras());
                break;

            case REQUEST_CODE_FOR_STEELYARD: // 抚触台
                handleConnectSteelyardEvent(data.getExtras());
                break;
        }
    }

    /**
     * 处理选择门店
     *
     * @param bundle
     */
    private void handleSelectShopEvent(Bundle bundle) {
        NatatoriumListPageEntity.ListBean model = (NatatoriumListPageEntity.ListBean) bundle.getSerializable("ShopModel");
        showShopInfo(model);
        HeartbeatManageSingleton.getInstance.stopAirWaterHeartbeat();
        mPresenter.getShopRealTimeDataByHeartbeat(model.getId());
    }

    @Override
    public void showShopInfo(NatatoriumListPageEntity.ListBean shop) {
        Glide.with(getContext())
                .load(shop.getLogoUrl())
                .centerCrop()
                .dontAnimate()
                //.placeholder(R.mipmap.default_user_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(shopIconRiv);

        shopNameTxt.setText(shop.getName());
        shopSelectedTimeTxt.setText(DateUtils.stampToDate3(System.currentTimeMillis()));

        selectShopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readyGoForResult(ACT_SelectShopList.class, REQUEST_CODE_FOR_SELECT);
            }
        });
    }

    /**
     * 处理链接泳圈
     *
     * @param bundle
     */
    private void handleConnectRingEvent(Bundle bundle) {
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            new AppSharedPreferences(mContext).putString(Constants.SWIM_RING_CODE, result);
            Constants.SWIMRINGCODE = result;
            mPresenter.getSwimRingBind(Constants.TOKEN, result, Constants.COMPANYID, Constants.BABYID);
        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            showToast("扫码失败，请重新尝试");
        }
    }

    /**
     * 处理抚触台
     *
     * @param bundle
     */
    private void handleConnectSteelyardEvent(Bundle bundle) {
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            mPresenter.getSteelyardLogin(result, Constants.TOKEN, Constants.BABYID);
        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
            showToast("扫码失败，请重新尝试");
        }
    }

    @Override
    public void onDestroyView() {
        HeartbeatManageSingleton.getInstance.stopAllHeartbeat();
        super.onDestroyView();
    }

    /**
     * 初始化界面与i清理数据
     */
    private void initializeInterfaceAndClearData() {
        HeartbeatManageSingleton.getInstance.stopAllHeartbeat();
        initializeALLConnectInterface();
    }

    private SpannableStringBuilder formatMMss(String timeStr) {
        if (TextUtils.isEmpty(timeStr))
            return null;
        int temp = Integer.valueOf(timeStr);
        int minute = temp / 60;
        //int second = temp % 60;
        return StringSpanUtils.init().addStr("已游泳")
                .addForegroundColorHighLight(getContext().getResources().getColor(R.color.ylt_style_orange), String.valueOf(minute))
                .addStr("分钟").build();
                //.addForegroundColorHighLight(getContext().getResources().getColor(R.color.ylt_style_orange), String.valueOf(second))
                //.addStr("秒").build();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initViewsAndEvents();
        }
    }
}
